package org.stratusdb.funsql.execute;

import org.stratusdb.error.Error;
import org.stratusdb.metadata.Connection;
import org.stratusdb.store.AbstractStore;
import org.stratusdb.types.TableType;
import org.stratusdb.types.TupleType;

public class StoreScan extends AbstractOperator {
	private static final long serialVersionUID = -3825578524159235895L;
	
	private AbstractStore store;
	private String url;
	private String user;
	private String passwd;
	private String query;
	private TupleType resultPrototype;
	
	//constructors
	public StoreScan(AbstractStore store, String url, String user, String passwd, String query, TupleType resultPrototype) {
		super();
		
		this.store = store;
		this.url = url;
		this.user = user;
		this.passwd = passwd;
		this.query = query;
		this.resultPrototype = resultPrototype;
	}

	public StoreScan(AbstractStore store, Connection con, String query, TupleType resultPrototype) {
		this(store,con.getUrl(),con.getUser(),con.getPasswd(),query,resultPrototype);
	}
	
	//getters and setters
	public AbstractStore getStore() {
		return store;
	}

	public void setStore(AbstractStore store) {
		this.store = store;
	}
	
	public Error getLastError() {
		return lastError;
	}

	public void setLastError(Error lastError) {
		this.lastError = lastError;
	}

	//operator methods
	@Override
	public Error open() {
		lastError = this.store.openConnection(url, user, passwd);
		if(lastError==Error.NO_ERROR){
			lastError = this.store.executeQuery(query, resultPrototype);
		}
		return lastError;
	}

	@Override
	public TableType next() {
		lastError = Error.NO_ERROR;
		TableType table = this.store.fetchResult();
		return table;
	}

	@Override
	public Error close() {
		lastError =  this.store.closeConnection();
		return lastError;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer("StoreScan : ");
		sb.append(this.url + " : " + query);
		return sb.toString();
	}
}
